#include <string>
#include <unistd.h>
#include "Mutex.hpp"
using namespace LockModule;

int ticket = 1000;
Mutex mtx;

void *Ticket(void* args)
{
    std::string name = static_cast<char*>(args);
    while(true)
    {
        // mtx.Lock();
        LockGuard lg(mtx); // 临时对象: 初始化时自动加锁, 出while循环时自动解锁(RAII风格的加锁方式)
        if(ticket > 0)
        {
            usleep(1000);

            std::cout << name << " buys a ticket: " << ticket << std::endl;
            ticket--;

            // mtx.Unlock();
            usleep(50);
        }
        else
        {
            // mtx.Unlock();
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, Ticket, (void*)"thread-1");
    pthread_create(&t2, nullptr, Ticket, (void*)"thread-2");
    pthread_create(&t3, nullptr, Ticket, (void*)"thread-3");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);

    return 0;
}